/*
@author: user
@date: 2022/6/29 14:18
@Version: 1.0
@last modifined by : user
@last Modifined time : 2022/6/29 14:18
*/

const statusCode = [403, 404, 500];
const defaultRequestConfig = {
  // 配置请求格式: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
  'Content-Type': 'application/x-www-form-urlencoded',
  'Accept': 'application/json, text/plain, */*',
  // 安全策略配置: https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP
  'Content-Security-Policy': 'policy',
};

const postRequest = async(url, data, requestHeaderInformation) => {
  try {
    const response = await window.fetch(url, {
      method: 'POST',
      headers: {
        ...defaultRequestConfig,
        ...requestHeaderInformation,
      },
      // 异步请求, 一个 Navigator.sendBeacon() 替代品.
      // 参考 fetch 参数之 keepalive: https://developer.mozilla.org/en-US/docs/Web/API/fetch#parameters
      // 参考 Navigator.sendBeacon() : https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon
      keepalive: true,
      body: data,
      mode: 'cors',
    });
    const { status, statusText } = response;
    if (statusCode.includes(response.status)) {
      window.location.href = `${window.location.origin}/#/${response.status}`
    }
    if (status !== 200) {
      exceptionGatewayStatus(status, statusText);
    }
    return await response.json();
  } catch (err) {
    console.error(err);
  }
};

const getRequest = async(url, requestHeaderInformation) => {
  try {
    const response = await window.fetch(url, {
      method: 'GET',
      headers: {
        ...defaultRequestConfig,
        ...requestHeaderInformation,
      },
      mode: 'cors',
    });
    const { status, statusText } = response;
    if (statusCode.includes(response.status)) {
      window.location.href = `${window.location.origin}/#/${response.status}`
    }
    if (status !== 200) {
      exceptionGatewayStatus(status, statusText);
    }
    return await response.json();
  } catch (err) {
    console.error(err);
  }
};

// 状态码参考: https://koa.bootcss.com/#response
function exceptionGatewayStatus(status, statusText) {
  switch (status) {
    case 302:
      throw new Error(`请求异常: 文件创建初始化`);
    case 303:
      throw new Error(`请求异常: 见其它页面`);
    case 304:
      throw new Error(`请求异常: 缓存未修改`);
    case 305:
      throw new Error(`请求异常: 使用代理服务器`);
    case 502:
      throw new Error(`请求异常: 错误的网关`);
    case 503:
      throw new Error(`请求异常: 暂停服务`);
    case 504:
      throw new Error(`请求异常: 网关超时`);
    case 505:
      throw new Error(`请求异常: 不支持http版本`);
    default:
      throw new Error(`Unexpected: ${status}: ${statusText}`);
  }
}

export {
  postRequest,
  getRequest
}
